package user

import (
	"context"
	// "fmt"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/resultx"
	"mall/service/backend/common/utils/pointy"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserProfileLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUserProfileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserProfileLogic {
	return &GetUserProfileLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetUserProfileLogic) GetUserProfile(in *user.GetProfileReq) (*user.UserProfileResp, error) {
	if in.UserId == nil || *in.UserId == 0 {
		return nil, resultx.StatusError(resultx.USER_ID_REQUIRED, "")
	}

	res, err := l.svcCtx.CurrentUser.FindOne(l.ctx, *in.UserId)
	if err != nil {
		return nil, err
	}

	preloadMap, eagerLoadMap := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)

	// logrus.Info(fmt.Sprintf("GetUserProfile preloadMap: %+v", preloadMap))
	// map[user:[Id] userMeta:[likeCount collectEntryCount collectEntryStatus collectEntryItems postPhotoCount photoNewStatus photoPostItems orderCount orderNewStatus reviewCount reviewNewStatus askedQuestionCount askedQuestionNewStatus answeredQuestionCount answeredQuestionNewStatus]]
	// logrus.Info(fmt.Sprintf("GetUserProfile eagerLoadMap: %+v", eagerLoadMap))
	// map[user:[userMeta]]

	userEntityName := model.RpcEntityNames.User
	_, hasSettingMap := model.RpcEntityPreloadMap[userEntityName]
	if !hasSettingMap {
		return &user.UserProfileResp{}, nil
	}

	var uid uint64 = res.ID
	resp := &user.UserProfileResp{
		UserId: pointy.GetPointer(uid),
	}

	subEntitySettingMap := make(map[string]map[string]*model.ColumnSetting)
	if eagerLoadEntities, hasEagerLoadEntities := eagerLoadMap[userEntityName]; hasEagerLoadEntities {
		for _, entity := range eagerLoadEntities {
			if entitySettingMap, hasEntitySettingMap := model.RpcEntityPreloadMap[entity]; hasEntitySettingMap {
				subEntitySettingMap[entity] = entitySettingMap
			}
		}
	}

	var birthdayHidden uint32
	userMetaEntityName := model.RpcEntityNames.UserMeta
	if entitySettingMap, hasEntitySettingMap := subEntitySettingMap[userMetaEntityName]; hasEntitySettingMap {
		if subPreloadFields, hasSubPreloadFields := preloadMap[userMetaEntityName]; hasSubPreloadFields {
			var metaKeys []any
			metaKeyMap := make(map[string]string)
			for _, field := range subPreloadFields {
				fieldSetting, hasFieldSetting := entitySettingMap[field]
				if hasFieldSetting && len(fieldSetting.Name) > 0 {
					metaKeys = append(metaKeys, fieldSetting.Name)
					metaKeyMap[fieldSetting.Name] = field
				}
			}
			metaKeys = append(metaKeys, "_birthday_hidden")

			metaFilterMap := make(map[string]map[string][]any)
			metaFilterMap[model.UserMetumColumns.UserID] = map[string][]any{
				"equalTo": {uid},
			}
			metaFilterMap[model.UserMetumColumns.MetaKey] = map[string][]any{
				"in": metaKeys,
			}
			metaList, _, err := l.svcCtx.CurrentUser.GetMeta(l.ctx, model.M{}, -1, metaFilterMap)
			if err != nil {
				if err == model.ErrNotFound {
					return &user.UserProfileResp{}, nil
				}

				return nil, err
			}

			if len(metaList) > 0 {
				for _, v := range metaList {
					if len(v.MetaKey) > 0 && v.MetaValue.Valid {
						if v.MetaKey == "_birthday_hidden" {
							if v.MetaValue.String == "1" {
								birthdayHidden = 1
							}
						} else if field, ok := metaKeyMap[v.MetaKey]; ok {
							resp.UserMeta = append(resp.UserMeta, &user.UserMetaInfo{
								Id:    pointy.GetPointer(v.MetaID),
								Key:   pointy.GetPointer(field),
								Value: pointy.GetPointer(v.MetaValue.String),
							})
						}
					}
				}
			}
		}
	}

	if in.PlatformId != nil {
		userProfile := &user.UserProfileInfo{
			Id: pointy.GetPointer(res.ID),
		}
		switch *in.PlatformId {
		case globalkey.ThirdPartyPlatformWechatMini:
			authFilterMap := make(map[string]map[string][]any)
			authFilterMap[model.UserAuthColumns.UserID] = map[string][]any{
				"equalTo": {res.ID},
			}
			authFilterMap[model.UserAuthColumns.PlatformID] = map[string][]any{
				"equalTo": {globalkey.ThirdPartyPlatformWechatMini},
			}
			authList, _, err := l.svcCtx.CurrentUser.GetAuthList(l.ctx, model.M{
				"pageSize": uint64(1),
			}, -1, authFilterMap)
			if err != nil || len(authList) == 0 {
				return nil, err
			}

			userAuth := authList[0]
			userProfile.Nickname = pointy.GetPointer(userAuth.Nickname)
			userProfile.Avatar = pointy.GetPointer(userAuth.Avatar)
			userProfile.Gender = pointy.GetPointer(uint32(userAuth.Gender))
			if birthdayHidden > 0 {
				userProfile.BirthdayHidden = pointy.GetPointer(birthdayHidden)
			} else {
				userProfile.Birthday = pointy.GetPointer(modelx.FormatNullDotTime(userAuth.Birthday, "2006-01-02"))
			}
		}

		accountFilterMap := make(map[string]map[string][]any)
		accountFilterMap[model.UserAccountColumns.UserID] = map[string][]any{
			"equalTo": {res.ID},
		}
		accountList, _, err := l.svcCtx.CurrentUser.GetAccountList(l.ctx, model.M{
			"pageSize": uint64(1),
		}, -1, accountFilterMap)
		if err != nil || len(accountList) == 0 {
			return nil, err
		}

		account := accountList[0]
		userProfile.Level = pointy.GetPointer(uint32(account.Level))

		resp.UserProfile = userProfile
	}

	return resp, nil
}
